import type { AppRouteModule } from '/@/router/types';
import apiHttpClient from '/@/shared/utils/api-http-client';
import { AppConsts } from '/@/abpPro/AppConsts';
import { LAYOUT } from '/@/router/constant';
import { DynamicMenuOpenEnum, DynamicMenuServiceProxy } from '/@/shared/service-proxies';
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
import { usePermissionStoreWithOut } from '/@/shared/store/vbenModules/permission';
import { arrayService } from '/@/shared';
const IFrame = () => import('/@/views/sys/iframe/FrameBlank.vue');

export class DynamicRoute {
  async getDynamicMenuList() {
    const _permissionStoreWithOut = usePermissionStoreWithOut();

    const _dynamicMenuService = new DynamicMenuServiceProxy(
      AppConsts.remoteServiceBaseUrl,
      apiHttpClient,
    );
    const routeConfig = (await _dynamicMenuService.getList()) || [];
    routeConfig.sort(function (x, y) {
      return x.sort - y.sort;
    });
    const dynamicRoute: AppRouteModule[] = [];

    // 将服务端的路由配置转换为前端的类型
    for (const item of routeConfig) {
      // 根据 templatePath 取name
      let name = item.name || '';
      if (name === '' && !!item.templatePath) {
        // 转小写
        const path = item.templatePath.toLowerCase();
        // 组件文件名不为index.vue，则取名称
        if (path.endsWith('.vue') && !path.endsWith('index.vue')) {
          name = path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
        }
        // 如果包含admin2，表示为新页面组件，组件名称需要追加news
        if (path.includes('/admin2/')) {
          name = name + '-news';
        }
      }

      // 如果templatePath为http，则将name设置为templatePath
      if (item.templatePath && item.templatePath.toLocaleLowerCase().startsWith('http')) {
        name = item.templatePath;
      }

      const temp: AppRouteModule = {
        id: item.id,
        parentId: item.parentId,
        name: name,
        path: name || '',
        isSystem: item.isSystem,
        openEnum: item.openEnum,
        meta: {
          title: item.text || '',
          orderNo: +item.sort,
          hideMenu: item.hide,
          icon: item.icon,
          permission: item.permissionCode,
          modelId: item.templatePath,
        },
        component: item.templatePath || undefined,
      };
      dynamicRoute.push(temp);
    }

    // 处理加载数据
    const modules = import.meta.glob('/src/**/*.{vue,ts}');
    for (const item of dynamicRoute) {
      if (item.openEnum == DynamicMenuOpenEnum.Iframe) {
        // Iframe 和 外部 给 IFrame
        item.component = IFrame;
        item.meta.frameSrc = item.path;
        item.path = item.name;
      } else if (item.openEnum == DynamicMenuOpenEnum.Outer) {
        item.component = IFrame;
      } else if (item.openEnum == DynamicMenuOpenEnum.Component) {
        // 系统路由给配置好路径
        const componentPath = item.component;
        item.component = modules[componentPath];
      }
      // else if (item.openEnum == DynamicMenuOpenEnum.Function) {
      //   // 根据模板给component
      //   item.component = () => import('/@/lowcode/custom-page/custom.vue');
      // }
      else if (item.component == 'tree') {
        item.component = () => import('/@/app/main/about/about.vue');
      }
    }

    // 一级路由
    const parentRoutesTemp = dynamicRoute.filter((item) => {
      return !item.parentId;
    });

    const parentRoutes = [...parentRoutesTemp];
    // 生成路由结构
    for (const item of parentRoutes) {
      this.permissionDeep(item, dynamicRoute);
    }

    // 给父级路由模板
    for (const route of parentRoutes) {
      // 什么意思？
      if (!route.path.startsWith('/') && route.openEnum !== DynamicMenuOpenEnum.Outer) {
        route.path = `/${route.path}`;
      }

      // 存在子级菜单，设置布局页
      if (route.children && route.children.length) {
        route.component = LAYOUT;
        continue;
      }

      // 不存在子级菜单,生成子级菜单
      const defaultCildren: AppRouteModule = {
        ...route,
        id: undefined,
        name: route.name,
        path: route.name,
        meta: { ...route.meta, hideMenu: true },
      };

      route.name = route.id;
      route.component = LAYOUT;
      route.path = '/main';
      route.meta.hideChildrenInMenu = true;
      route.redirect = route.path + '/' + defaultCildren.name;
      route.children = [defaultCildren];
    }

    const dynamicRoutes = [PAGE_NOT_FOUND_ROUTE, ...parentRoutes];
    _permissionStoreWithOut.setDynamicMenuList(dynamicRoutes);
  }

  // 深拷贝
  permissionDeep(per, perArry) {
    const sonPerArry = perArry.filter((p) => p.parentId == per.id);
    if (sonPerArry.length > 0) {
      sonPerArry.map((item) => {
        if (
          item.openEnum !== DynamicMenuOpenEnum.Outer &&
          item.openEnum !== DynamicMenuOpenEnum.Iframe
        ) {
          item.path = item.path.split('/')[item.path.split('/').length - 1];
        }
      });
      per.children = sonPerArry;
      for (let i = 0; i < sonPerArry.length; i++) {
        sonPerArry[i] = this.permissionDeep(sonPerArry[i], perArry);
      }
    }
    return per;
  }
}

export default new DynamicRoute();
